package org.zuel.boot.demo.component;


import org.apache.shiro.authc.*;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zuel.boot.demo.constant.LoginType;
import org.zuel.boot.demo.exception.InvalidAccountException;
import org.zuel.boot.demo.model.DemoUser;
import org.zuel.boot.demo.service.IAuthQueryService;
import org.zuel.boot.demo.util.bcrypt.BCryptPasswordEncoder;

import java.util.List;
@Component
public class UserPasswordRealm extends UserAuthRealm {

    private static final Logger log = LoggerFactory.getLogger(UserPasswordRealm.class);

    @Autowired
    private IAuthQueryService authQueryService;


    @Override
    public String getName() {
        return LoginType.USER_PASSWORD.getType();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        if (token instanceof LoginToken) {
            return ((LoginToken) token).getLoginType() == LoginType.USER_PASSWORD;
        } else {
            return false;
        }
    }

    @Override
    public void setAuthorizationCacheName(String authorizationCacheName) {
        super.setAuthorizationCacheName(authorizationCacheName);
    }

    @Override
    protected void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //此方法重写了父类的父类的方法
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password=new String(upToken.getPassword());
        List<DemoUser> userList = authQueryService.queryUsername(username);
        if (userList.size() == 0) {
            throw new UnknownAccountException("用户未注册");
        }
        DemoUser user = userList.get(0);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, user.getPassword())) {
            throw new InvalidAccountException("用户名或密码错误");
        }
        return new SimpleAuthenticationInfo(user, password, getName());
    }

}
